import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }


objType = {'database':'database','table':'table','field':'field'}


private buildOrigin(type:string,value:string){
  return {'type':type,'value':value};
}


private convertFlat2FieldTreeWithKey(rs:any[]):any[]{
  let rsDB = [];
  let rsTable = [];
  
  // 构建去重的数据库数组、表数组
  rs.forEach(ele => {
    // 构建去重的数据库数组
    if(rsDB.length<=0) rsDB.push({'dbName':ele.schema_name,'autoKey':ele.auto_key});
    let dbExists = rsDB.some(
      (dbRow,index,array) =>{
        return dbRow.dbName === ele.schema_name;
      }
    )
    if( !dbExists ) rsDB.push({'dbName':ele.schema_name,'autoKey':ele.auto_key});

    // 构建去重的表数组
    if(rsTable.length<=0) rsTable.push({'dbName':ele.schema_name,'tableName':ele.table_name,'autoKey':ele.auto_key});
    let tableExists = rsTable.some((ele1,index,array)=>{
      return ele1.tableName === ele.table_name && ele1.dbName === ele.schema_name ;
    })
    if( !tableExists ) rsTable.push({'dbName':ele.schema_name,'tableName':ele.table_name,'autoKey':ele.auto_key});

  });

  // 没有数据库则不创建，退出
  if(rsDB.length<=0){
    console.log('没有数据库！');
    return;
  }

  let tree = [];
  
  rsDB.forEach(eleDB => {// 遍历数据库数组
    // 构建单个数据库节点 - 子节点留空
    // let dbKey = "schema_name=" + eleDB;
    let dbNode = {'title':eleDB.dbName,'key':eleDB.autoKey,'children':[],
      'origin':this.buildOrigin(this.objType.database,eleDB.dbName)};// 本地枚举设置类型 = 数据库
    
    let tables = rsTable.filter((item)=>{// 获取当前数据库下的所有表
      return item.dbName === eleDB.dbName;
    })

    let tableNodes = [];
    tables.forEach(eleTable => {
      let rsFields = rs.filter((item)=>{// 从原始记录集中获取指定数据库、表下的所有字段
        return item.table_name === eleTable.tableName && item.schema_name === eleTable.dbName;
      })

      let fieldNodes = [];
      rsFields.forEach((eleField) => {
        let title = eleField.column_name + ' - ' + eleField.column_type + ' - ' + eleField.column_comment;
        fieldNodes.push({'title':title,'key':eleField.auto_key,'isLeaf':'true','origin':this.buildOrigin(this.objType.field,eleField.column_name)});
      });
      let tableNode = {'title':eleTable.tableName,'key':eleTable.autoKey,'children':fieldNodes,'origin':this.buildOrigin(this.objType.table,eleTable.tableName)};
      tableNodes.push(tableNode);
    });

    dbNode.children = tableNodes;
    tree.push(dbNode);
  });


  return tree;
}




}
